//https://leetcode.cn/problems/binary-tree-postorder-traversal/

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        TreeNode* cur = root;
        stack<TreeNode*> st;
        vector<int> ret;
        TreeNode* prev = nullptr;  //当前节点访问的上一个节点

        while (cur || !st.empty())
        {
            //左节点及左路节点入栈
            while (cur)
            {
                st.push(cur);
                cur = cur->left;
            }

            //右子树为空或者访问的上一个节点为右节点，说明该节点为根节点
            TreeNode* top = st.top();
            if (top->right == nullptr || top->right == prev)
            {
                ret.push_back(top->val);
                st.pop();
                prev = top;
            }
            else
            {
                cur = top->right;
            }
        }

        return ret;

    }
};